package com.liaoyin.travel.service.team;

import com.github.pagehelper.PageHelper;
import com.liaoyin.travel.base.constant.VariableConstants;
import com.liaoyin.travel.view.user.UserBackView;
import com.liaoyin.travel.view.user.UserTeamBackView;
import com.liaoyin.travel.view.user.UserTeamView;
import com.liaoyin.travel.view.user.UserView;
import com.liaoyin.travel.base.service.BaseService;
import com.liaoyin.travel.bean.UserInfo;
import com.liaoyin.travel.dao.team.TeamMapper;
import com.liaoyin.travel.entity.FileUpload;
import com.liaoyin.travel.entity.Users;
import com.liaoyin.travel.entity.team.Team;
import com.liaoyin.travel.entity.team.TeamWorker;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.service.*;
import com.liaoyin.travel.util.FileUploadUtil;
import com.liaoyin.travel.util.PartyUtil;
import com.liaoyin.travel.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @项目名：旅投
 * @作者：lijing
 * @描述：部门列表
 * @日期：Created in 2018/6/20 14:55
 */
@Service
public class TeamService extends BaseService<TeamMapper, Team> {

    @Autowired
    private TeamWorkerService teamWorkerService;

    @Autowired
    private UsersService usersService;
    @Autowired
    private UserTeamService userTeamService;

    /*****
     *
     * @方法名：selectTeamList
     * @描述： 查询部门列表
     * @作者： lijing
     * @日期： 2019年7月12日
     */
    public List<Team> selectTeamList(Integer num, Integer size,
                                     String teamName, String teamLevel, String parentId, String teamCode, String isUsing) {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if (curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();

        PageHelper.startPage(num, size);
        List<Team> list = this.mapper.selectTeamList(teamName, teamLevel, parentId, teamCode, isUsing, scenicId);
        if (list != null && list.size() > 0) {
            list.stream().forEach((t) -> {
                List<TeamWorker> workerList = this.teamWorkerService.selectTeamWorkerListByTeamId(t.getId());
                t.setWorkerList(workerList);
            });
        }
        return list;
    }

    /****
     *
     * @方法名：insertOrUpdateTeam
     * @描述： 新增或修改部门
     * @作者： lijing
     * @日期： 2019年7月12日
     */
    @Transactional(rollbackFor = BusinessException.class)
    public void insertOrUpdateTeam(Team team) {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if (curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();

        if (null != team.getTeamContext() && team.getTeamContext().length() > 200) {
            throw new BusinessException("string.is.toLong");
        }
        //部门id
        String teamId = team.getId();

        //部门名称判断重复
        String teamName = team.getTeamName();
        judgeTeamNameIsReDo(teamName, scenicId, teamId);

        //部门编码判断重复
        String teamCode = team.getTeamCode();
        judgeTeamCodeIsReDo(teamCode, scenicId, teamId);

        //非一级部门必须得判断上级部门不能为空
        if(team.getTeamLevel().intValue()!=1){
            String parentId = team.getParentId().trim();
            if(parentId==null || parentId.equals("")){
                throw new BusinessException("parentId.is.null");
            }
        }


      if (teamId != null && !"".equals(teamId)) {
            /** 修改 **/
            this.mapper.updateByPrimaryKeySelective(team);
            if (team.getWorkerList() != null && team.getWorkerList().size() > 0) {
                this.teamWorkerService.insertTeamWorker(team.getWorkerList(), team.getId());
            }
        } else {
            /** 新增 **/
            teamId = UUIDUtil.getUUID();
            team.setCreatTime(new Date());
            team.setId(teamId);
            team.setIsDelete((short) 0);
            team.setIsUsing((short) 1);
            team.setScenicId(scenicId);
            this.mapper.insertSelective(team);
            if (team.getWorkerList() != null && team.getWorkerList().size() > 0) {
                this.teamWorkerService.insertTeamWorker(team.getWorkerList(), teamId);
            }
        }
    }

    /**
     * @方法名：judgeTeamCodeIsReDo
     * @描述： 判断部门编码是否重复，若重复抛出异常
     * @作者： kjz
     * @日期： Created in 2020/3/7 12:45
     */
    private void judgeTeamCodeIsReDo(String teamCode, String scenicId, String teamId) {
        List<Team> teamList = this.mapper.selectTeamListByCode(teamCode, scenicId, teamId);
        if (teamList.size() > 0) {
            throw new BusinessException("teamCode.is.exist");
        }
    }

    /**
     * @方法名：judgeTeamNameIsReDo
     * @描述： 判断部门名称是否重复，若重复，则抛出异常
     * @作者： kjz
     * @日期： Created in 2020/3/7 12:42
     */
    private void judgeTeamNameIsReDo(String teamName, String scenicId, String teamId) {
        List<Team> teamList = this.mapper.selectTeamListByName(teamName, scenicId, teamId);
        if (teamList.size() > 0) {
            throw new BusinessException("teamName.is.exist");
        }
    }

    /****
     *
     * @方法名：selectTeamById
     * @描述： 通过id查询
     * @作者： lijing
     * @日期： 2019年7月12日
     */
    public Team selectTeamById(String id) {
        if (id == null) {
            throw new BusinessException("id.is.null");
        }
        Team team = this.mapper.selectByPrimaryKey(id);
        if (team != null) {
            List<TeamWorker> workerList = this.teamWorkerService.selectTeamWorkerListByTeamId(team.getId());
            team.setWorkerList(workerList);
            workerList = null;
        }
        return team;
    }

    /**
     * 　* @description: TODO 根据部门名称查询部门id
     * 　* @param [name]
     * 　* @return com.liaoyin.travel.entity.team.Team
     * 　* @throws
     * 　* @author privatePanda777@163.com
     * 　* @date 2019/7/25 17:09
     *
     */
    public Team selectTeamByName(String name) {
        if (null == name) {
            throw new BusinessException("team_name.is.null");
        }
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if (curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();
        return this.mapper.selectTemaByName(name, scenicId);
    }


    /**
     * @方法名：selectTeamUserViewByAll
     * @描述： 按部门分组查询员工信息
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/13 17:50
     */
    public List<UserTeamView> selectTeamUserViewByAll() {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if (curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();

        //1.组装最后要返回的数据
        List<UserTeamView> result = new ArrayList<>();
        //2.查询所有部门
        List<Team> teamList = this.mapper.selectTeamByAll(scenicId);
        teamList.forEach(team -> {
            String teamId = team.getId();
            String teamName = team.getTeamName();
            List<Users> usersList = this.usersService.selectUsersListByTeamId(teamId, scenicId);
            List<UserView> userViews = new ArrayList<>();
            if (!usersList.isEmpty()) {
                usersList.forEach(users -> {
                    UserView userView = new UserView();
                    String userId = users.getId();
                    String nickName = users.getNickName();
                    //头像
                    String headPicId = users.getHeadPicId();
                    FileUpload fileUpload = FileUploadUtil.getFileUpload(headPicId);
                    String headPicUrl = null;
                    if (fileUpload != null) {
                        headPicUrl = fileUpload.getUrl();
                    }
                    System.err.println("headPicUrl=" + headPicUrl);
                    userView.setHeadPicUrl(headPicUrl);
                    //职务
                    String holdOffice = users.getAssumeOfficeDisplay();
                    userView.setHoldOffice(holdOffice);
                    userView.setUserId(userId);
                    userView.setNickName(nickName);
                    userViews.add(userView);
                });
            }
            UserTeamView userTeamView = new UserTeamView();
            userTeamView.setTeamId(teamId);
            userTeamView.setTeamName(teamName);
            userTeamView.setUserViewList(userViews);
            result.add(userTeamView);
        });
        return result;
    }

    /**
     * @方法名：selectTeamUserBackViewByAll
     * @描述： 后台管理系统特供-按部门分组查询员工信息
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/22 16:31
     */
    public List<UserTeamBackView> selectTeamUserBackViewByAll() {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if (curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();
        //1.组装最后要返回的数据
        List<UserTeamBackView> result = new ArrayList<>();
        //2.查询所有部门
        List<Team> teamList = this.mapper.selectTeamByAll(scenicId);
        teamList.forEach(team -> {
            String teamId = team.getId();
            String teamName = team.getTeamName();
            List<Users> usersList = this.usersService.selectUsersListByTeamId(teamId, scenicId);
            List<UserBackView> userBackViews = new ArrayList<>();
            if (!usersList.isEmpty()) {
                usersList.forEach(users -> {
                    UserBackView userBackView = new UserBackView();
                    String userId = users.getId();
                    String nickName = users.getNickName();
                    //头像
                    String headPicId = users.getHeadPicId();
                    FileUpload fileUpload = FileUploadUtil.getFileUpload(headPicId);
                    String headPicUrl = null;
                    if (fileUpload != null) {
                        headPicUrl = fileUpload.getUrl();
                    }
                    System.err.println("headPicUrl=" + headPicUrl);
                    userBackView.setHeadPicUrl(headPicUrl);
                    //职务
                    String holdOffice = users.getAssumeOfficeDisplay();
                    userBackView.setHoldOffice(holdOffice);
                    userBackView.setUserId(userId);
                    //组装成带职务的名称
                    String nikeHoldOfficeName = nickName + "("+holdOffice+")";
                    userBackView.setName(nikeHoldOfficeName);
                    userBackViews.add(userBackView);
                });
            }
            UserTeamBackView userTeamBackView = new UserTeamBackView();
            userTeamBackView.setTeamId(teamId);
            userTeamBackView.setName(teamName);
            userTeamBackView.setChildren(userBackViews);
            result.add(userTeamBackView);
        });
        return result;
    }

    public List<Team> selectAllTeam() {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if (curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();
        return this.mapper.selectTeamByAll(scenicId);
    }

    /**
     * 通过ID批量删除
     *
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(List<String> ids) {
        //判断部门是否已经关联员工
        judgeTeamIsCorrelationStaff(ids);
        //批量删除部门
        this.mapper.deleteByidsBatch(ids);
        //批量删除部门-工种关系
        this.mapper.deleteTeamWorkerByTeamIds(ids);
        //批量删除部门-用户关系
        return userTeamService.deleteUserTeamByTeamIds(ids);

    }

    /**
     * 判断部门是否已经关联员工
     *
     * @param ids
     */
    private void judgeTeamIsCorrelationStaff(List<String> ids) {
        List<String> teams = userTeamService.judgeTeamIsCorrelationStaff(ids);
        if (teams != null && teams.size() > 0) {
            throw new BusinessException("Team.is.Correlation", "删除失败！部门" + teams.toString() + "已经关联员工！");
        }
    }

    /**
     * @方法名：selectTeamByParentId
     * @描述： 根据父id查询子级的
     * @作者： kjz
     * @日期： Created in 2020/4/8 18:33
     */
    public List<Team> selectTeamByParentId(String teamId) {
        return this.mapper.selectTeamByParentId(teamId);
    }
}
